package com.example.spring.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.spring.demo.common.model.PageBean;
import com.example.spring.demo.common.model.req.GoodsOrderParam;
import com.example.spring.demo.common.model.vo.GoodsOrderVo;
import com.example.spring.demo.entity.Goods;
import com.example.spring.demo.entity.GoodsOrder;
import com.example.spring.demo.mapper.GoodsOrderMapper;
import com.example.spring.demo.service.GoodsOrderService;
import com.example.spring.demo.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2024/12/31 10:48
 **/
@Service
public class GoodsOrderServiceImpl extends ServiceImpl<GoodsOrderMapper,
        GoodsOrder> implements GoodsOrderService {
    @Autowired
    private GoodsService goodsService;
    @Override
    @Transactional
    public void replaceOrder(GoodsOrder goodsOrder) { //订单数据
//1、插入订单数据
        goodsOrder.setCreateTime(new Date());
        int insert = this.baseMapper.insert(goodsOrder);
//2、更新商品状态
        if(insert > 0){
            UpdateWrapper<Goods> query = new UpdateWrapper<>();
            query.lambda().set(Goods::getSellStatus,"1")
                    .set(Goods::getStatus,"1")
                    .eq(Goods::getGoodsId,goodsOrder.getGoodsId());
            goodsService.update(query);
        }
    }

    //订单列表
    @Override
    public PageBean<GoodsOrderVo> getPageList(GoodsOrderParam param) {
        PageBean<GoodsOrderVo> pageBean = new PageBean<>();
//1、查询总条数
        Long totalCount = this.baseMapper.findTotalCount(param);
//2、查询数据
        if(totalCount > 0){
//3、设置分页数据
            pageBean.setCurPage(param.getCurPage());
            pageBean.setPageSize(param.getPageSize());
            pageBean.setTotalCount(totalCount);
            pageBean.setTotalPage(totalCount.intValue() % param.getPageSize() ==
                    0 ?
                    totalCount.intValue() / param.getPageSize() :
                    totalCount.intValue() / param.getPageSize()+ 1);//总页数
        }
//4、设置当前页
        param.setCurPage((param.getCurPage() - 1) * param.getPageSize());
//5、查询数据
        List<GoodsOrderVo> list = this.baseMapper.getList(param);
        pageBean.setData(list);
        return pageBean;
    }
}